public class Solution794 {
    public boolean validTicTacToe(String[] board) {
        int x=0,o=0;
        for (String s : board) {
            for (int i=0;i<3;i++){
                if (s.charAt(i)=='X'){
                    x++;
                }else if (s.charAt(i)=='O'){
                    o++;
                }
            }
        }
        if (x-o==0 || x-o==1){
            int xWin=0,oWin=0;
            for (int i=0;i<3;i++) {
                if (board[i].charAt(0) == board[i].charAt(1) && board[i].charAt(1) == board[i].charAt(2)){
                    if (board[i].charAt(0)=='X'){
                        xWin=1;
                    }else if (board[i].charAt(0)=='O'){
                        oWin=1;
                    }
                }
            }
            for (int i=0;i<3;i++) {
                if (board[0].charAt(i) == board[1].charAt(i) && board[1].charAt(i) == board[2].charAt(i)){
                    if (board[0].charAt(i)=='X'){
                        xWin=1;
                    }else if (board[0].charAt(i)=='O'){
                        oWin=1;
                    }
                }
            }
            if (board[0].charAt(0)==board[1].charAt(1)&&board[1].charAt(1)==board[2].charAt(2)){
                if (board[0].charAt(0)=='X'){
                    xWin=1;
                }else if (board[0].charAt(0)=='O'){
                    oWin=1;
                }
            }
            if (board[0].charAt(2)==board[1].charAt(1)&&board[1].charAt(1)==board[2].charAt(0)){
                if (board[0].charAt(2)=='X'){
                    xWin=1;
                }else if (board[0].charAt(2)=='O'){
                    oWin=1;
                }
            }
            if (x-o==1&&oWin==1 || x==o&&xWin==1){
                return false;
            }else{
                return true;
            }
        }else{
            return false;
        }
    }

    public static void main(String[] args) {
        System.out.println(new Solution794().validTicTacToe(new String[]{"OOO","   ","XXX"}));
    }
}
